/**
 * 
 */
package com.redside.dao.hibernate;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Expression;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.redside.dao.EmailDao;
import com.redside.model.Email;

/**
 * @author PCHAPMAN
 *
 */
public class EmailDaoHibernate extends HibernateDaoSupport implements EmailDao {

    /* (non-Javadoc)
     * @see gov.oregon.wems.dao.email.email.EmailDao#delete(gov.oregon.wems.model.email.Email)
     */
    public void delete(Email email) {
        getHibernateTemplate().delete(findById(email.getId()));
    }

    /* (non-Javadoc)
     * @see gov.oregon.wems.dao.email.email.EmailDao#findAll()
     */
    @SuppressWarnings("unchecked")
    public List<Email> findAll() {
        return getHibernateTemplate().find("from Email order by county_id, emailTypeId");
    }
    
    /* (non-Javadoc)
     * @see gov.oregon.wems.dao.email.email.EmailDao#findAllByType(Long id)
     */
    @SuppressWarnings("unchecked")
    public List<Email> findAllByType(Long id){
        return getHibernateTemplate().find("from Email where emailType = ?",id);
    }

    /* (non-Javadoc)
     * @see gov.oregon.wems.dao.email.email.EmailDao#findById(java.lang.Long)
     */
    public Email findById(Long id) {
        logger.debug("Do we have an id: "+id);
        Email email = (Email) getHibernateTemplate().get(Email.class, id);
        if (email == null) {
            throw new ObjectRetrievalFailureException(Email.class, id);
        }
        return email;
    }

    /* (non-Javadoc)
     * @see gov.oregon.wems.dao.email.email.EmailDao#findByIdAndCountyId(java.lang.Long, java.lang.String)
     */
    @SuppressWarnings("unchecked")
	public List<Email> findByIdAndCountyId(Long id, String countyId) {
        Criteria criteria = getSession().createCriteria(Email.class);
        criteria.add(Expression.eq("emailTypeId", id));
        criteria.add(Expression.eq("countyLkp.countyId", countyId));
        List<Email> emails = criteria.list();

        return emails;        
    }

    /* (non-Javadoc)
     * @see gov.oregon.wems.dao.email.email.EmailDao#save(gov.oregon.wems.model.email.Email)
     */
    public Email save(Email email) {
        getHibernateTemplate().saveOrUpdate(email);
        getHibernateTemplate().flush();
        return findById(email.getId());
    }

}